package scaladuct.particles.file

import java.lang.{String}
import scaladuct.{Name, Starter}
import java.io.{OutputStream, InputStream, FileInputStream, File}

/**
 * <p>
 * Created by IntelliJ IDEA.
 * User: zslajchrt
 * Date: Aug 19, 2010
 * Time: 5:17:34 PM
 */

class FileFactory extends Starter[Starter[FileInputStream]] {
  def destroy(instance: Starter[FileInputStream]) = {
    println("destroying " + instance)
  }

  def newInstance(): Starter[FileInputStream] = {
    phaseGetFilePath(null)
  }

  def phaseGetFilePath(@Name("filePath") filePath: String): Starter[FileInputStream] = {
    new Starter[FileInputStream] {
      def newInstance() = new FileInputStream(filePath)

      def destroy(instance: FileInputStream) = instance.close
    }
  }
}

object StarterUtils {
  def perform(statement : => Any): Option[Throwable] = {
    try {
      statement
      None
    }
    catch {
      case t: Throwable => Some(t)
    }
  }
}

class StreamProcessFactory extends Starter[Starter[Runnable]] {
  def newInstance() = phaseGetStreams(null, null)

  def phaseGetStreams(in: Starter[InputStream], out: Starter[OutputStream]) = {
    new Starter[Runnable] {

      class Batch extends Runnable {
        val i = in.newInstance
        val o = out.newInstance

        def run = {}

        def destroy = {
          StarterUtils.perform(i.close)
          StarterUtils.perform(o.close)
        }
      }

      def newInstance() = new Batch

      def destroy(instance: Runnable) = {
        //instance.destroy
      }


    }

  }

  def destroy(instance: Starter[Runnable]) = {
    
  }

}